<template>
  <main class="h-full flex flex-col max-w-7xl mx-auto px-6 pb-2">
    <!-- 顶部标题和状态 -->
    <div class="flex-shrink-0 mb-2">
      <div class="flex items-center gap-2">
        <div class="w-2 bg-yellow-200 h-8"></div>
        <div class="text-2xl font-bold">图文组合导出</div>
      </div>

      <div class="text-gray-600">
        已选择 {{ selectedImages.length }} 张图片:
      </div>
    </div>

    <!-- Tabs 切换 -->
    <Tabs v-model="activeTab" class="flex-1 min-h-0">
      <TabsList class="grid w-full grid-cols-2">
        <TabsTrigger value="manual">手动导出</TabsTrigger>
        <TabsTrigger value="ai">AI 导出</TabsTrigger>
      </TabsList>

      <!-- 手动导出模式 -->
      <TabsContent value="manual" class="flex gap-6 flex-1 min-h-0">
        <!-- 左侧配置区域 -->
        <ScrollArea
          class="w-100 rounded-md border p-4 h-[600px] flex-shrink-0 bg-white"
        >
          <div class="space-y-6">
            <!-- 选中图片展示 -->
            <div>
              <div class="flex items-center gap-2 mb-2">
                <div class="text-lg font-semibold mb-1">选中图片</div>
                <svg
                  t="1753020669006"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="25117"
                  width="30"
                  height="30"
                >
                  <path
                    d="M125.9 185h772.2v653.9H125.9z"
                    fill="#1F53CC"
                    p-id="25118"
                  ></path>
                  <path
                    d="M164.7 217.2h694.6v516.7H164.7z"
                    fill="#FECD44"
                    p-id="25119"
                  ></path>
                  <path
                    d="M458.9 734l-8.6-43.8-101.5-102.8-135 146.6z"
                    fill="#FC355D"
                    p-id="25120"
                  ></path>
                  <path
                    d="M306.9 348.7m-66.7 0a66.7 66.7 0 1 0 133.4 0 66.7 66.7 0 1 0-133.4 0Z"
                    fill="#FFFFFF"
                    p-id="25121"
                  ></path>
                  <path
                    d="M384.6 734h474.7V608.8L687.8 400.1z"
                    fill="#FC355D"
                    p-id="25122"
                  ></path>
                  <path
                    d="M422.5 662l-37.9 72 52.1-57.5z"
                    fill="#BF2847"
                    p-id="25123"
                  ></path>
                  <path
                    d="M302.5 778.9h418.9v16.7H302.5z"
                    fill="#00F0D4"
                    p-id="25124"
                  ></path>
                </svg>
              </div>

              <div class="flex gap-3 overflow-x-auto pb-2">
                <div
                  v-for="(img, index) in selectedImages"
                  :key="img.id"
                  class="relative flex-shrink-0"
                >
                  <div
                    class="w-40 h-40 rounded-lg overflow-hidden border-2 border-gray-200"
                  >
                    <img
                      :src="img.url"
                      :alt="img.name"
                      class="w-full h-full object-cover"
                    />
                  </div>
                </div>
              </div>
            </div>
            <!-- 模板选择 -->
            <div>
              <div class="flex items-center gap-2 mb-2">
                <div class="text-lg font-semibold mb-1">模板选择</div>
                <svg
                  t="1753021977676"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="46287"
                  width="30"
                  height="30"
                >
                  <path
                    d="M840.3968 512h-180.3776c-45.2608 0-81.92-36.6592-81.92-81.92V199.7824c0-45.2608 36.6592-81.92 81.92-81.92h180.3776c45.2608 0 81.92 36.6592 81.92 81.92V430.08c0 45.2608-36.6592 81.92-81.92 81.92z"
                    fill="#ffa115"
                    p-id="46288"
                  ></path>
                  <path
                    d="M367.2576 87.1424H186.88c-62.1056 0-112.64 50.5344-112.64 112.64v624.4352c0 62.1056 50.5344 112.64 112.64 112.64h180.3776c62.1056 0 112.64-50.5344 112.64-112.64V199.7824c0-62.1056-50.5344-112.64-112.64-112.64z m51.2 737.0752c0 28.2112-22.9888 51.2-51.2 51.2H186.88c-28.2112 0-51.2-22.9888-51.2-51.2V199.7824c0-28.2112 22.9888-51.2 51.2-51.2h180.3776c28.2112 0 51.2 22.9888 51.2 51.2v624.4352zM840.3968 87.1424h-180.3776c-62.1056 0-112.64 50.5344-112.64 112.64V430.08c0 62.1056 50.5344 112.64 112.64 112.64h180.3776c62.1056 0 112.64-50.5344 112.64-112.64V199.7824c0-62.1056-50.5344-112.64-112.64-112.64z m51.2 342.9376c0 28.2112-22.9888 51.2-51.2 51.2h-180.3776c-28.2112 0-51.2-22.9888-51.2-51.2V199.7824c0-28.2112 22.9888-51.2 51.2-51.2h180.3776c28.2112 0 51.2 22.9888 51.2 51.2V430.08zM840.3968 611.0208h-180.3776c-62.1056 0-112.64 50.5344-112.64 112.64v100.5568c0 62.1056 50.5344 112.64 112.64 112.64h180.3776c62.1056 0 112.64-50.5344 112.64-112.64v-100.5568c0-62.1056-50.5344-112.64-112.64-112.64z m51.2 213.1968c0 28.2112-22.9888 51.2-51.2 51.2h-180.3776c-28.2112 0-51.2-22.9888-51.2-51.2v-100.5568c0-28.2112 22.9888-51.2 51.2-51.2h180.3776c28.2112 0 51.2 22.9888 51.2 51.2v100.5568z"
                    fill="#474A54"
                    p-id="46289"
                  ></path>
                </svg>
              </div>

              <div class="grid grid-cols-2 gap-3">
                <button
                  v-for="template in templates"
                  :key="template.key"
                  @click="selectedTemplate = template.key"
                  class="flex flex-col items-center gap-2 p-3 rounded-lg border transition-colors"
                  :class="
                    selectedTemplate === template.key
                      ? 'bg-yellow-400 text-white border-yellow-400'
                      : 'bg-white text-gray-700 border-gray-200 hover:border-gray-300'
                  "
                >
                  <div class="w-8 h-8 flex items-center justify-center">
                    <svg
                      class="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <rect
                        x="3"
                        y="3"
                        :width="template.iconWidth"
                        :height="template.iconHeight"
                        rx="2"
                        stroke-width="2"
                      />
                    </svg>
                  </div>
                  <div class="text-sm font-medium">{{ template.label }}</div>
                  <div class="text-xs opacity-75">{{ template.ratio }}</div>
                </button>
              </div>
            </div>
            <!-- 文案编辑 -->
            <div>
              <div class="flex items-center gap-2 mb-2">
                <div class="text-lg font-semibold mb-1">文案编辑</div>
                <svg
                  t="1753021904715"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="44053"
                  width="30"
                  height="30"
                >
                  <path
                    d="M911 498.75c-34.33-32.43-74.86-8.66-74.86 24.57v354.19a21.75 21.75 0 0 1-21.69 21.69h-665.6a21.75 21.75 0 0 1-21.69-21.69V211.89a21.75 21.75 0 0 1 21.69-21.69h353.47c20.7 0 39.4-16.85 40.65-37.52A40 40 0 0 0 503 110.2H148.85A101.69 101.69 0 0 0 47.16 211.89v665.62A101.69 101.69 0 0 0 148.85 979.2h726.5a40.82 40.82 0 0 0 40.82-40.82V510.67a18.84 18.84 0 0 0-5.17-11.92z"
                    fill="#1FD389"
                    p-id="44054"
                  ></path>
                  <path
                    d="M965 221.55l-165-165a40 40 0 0 0-56.57 0l-434.56 434.7a40 40 0 0 0-9.47 15.06l-87.94 251.07a40 40 0 0 0 50.65 51.09L515 722.34a40 40 0 0 0 15.39-9.58L965 278.12a40 40 0 0 0 0-56.57zM314.14 706.24l57.75-164.88 2-2L482.31 647.7l-1.91 1.91z m189.38-79.75L395.14 518.11 771.8 141.45l108.38 108.38z"
                    fill="#FED805"
                    p-id="44055"
                  ></path>
                  <path
                    d="M532.58 524.57a15 15 0 0 0 21.21 0l263-263a15 15 0 0 0-21.21-21.21l-263 263a15 15 0 0 0 0 21.21z"
                    fill="#FED805"
                    p-id="44056"
                  ></path>
                  <path
                    d="M506.200929 550.946243m-10.606602 10.606601a15 15 0 1 0 21.213204-21.213203 15 15 0 1 0-21.213204 21.213203Z"
                    fill="#FED805"
                    p-id="44057"
                  ></path>
                </svg>
              </div>

              <textarea
                v-model="copywritingText"
                placeholder="请输入文案内容..."
                class="w-full p-3 border border-gray-200 rounded-lg resize-none"
                rows="8"
              ></textarea>
              <div class="flex justify-end mt-2">
                <span class="text-xs text-gray-500"
                  >{{ copywritingText.length }} 字符</span
                >
              </div>
            </div>
            <!-- 导出设置区（shadcn-vue风格） -->
            <div>
              <div class="flex items-center gap-2">
                <div class="text-lg font-semibold mb-1">更多设置</div>
                <svg
                  t="1753021819802"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="42023"
                  width="30"
                  height="30"
                >
                  <path
                    d="M765.866667 518.4m-151.466667 0a151.466667 151.466667 0 1 0 302.933333 0 151.466667 151.466667 0 1 0-302.933333 0Z"
                    fill="#FCCA1E"
                    p-id="42024"
                  ></path>
                  <path
                    d="M258.133333 518.4m-151.466666 0a151.466667 151.466667 0 1 0 302.933333 0 151.466667 151.466667 0 1 0-302.933333 0Z"
                    fill="#93A8FF"
                    p-id="42025"
                  ></path>
                  <path
                    d="M514.133333 512m-151.466666 0a151.466667 151.466667 0 1 0 302.933333 0 151.466667 151.466667 0 1 0-302.933333 0Z"
                    fill="#2953FF"
                    p-id="42026"
                  ></path>
                </svg>
              </div>

              <div class="mb-4 space-y-3">
                <div>
                  <Label class="block my-2">水印文字</Label>
                  <Input v-model="watermarkText" placeholder="请输入水印" />
                </div>
                <div>
                  <Label class="block my-2">透明度</Label>
                  <Slider
                    v-model="watermarkOpacity"
                    :min="0"
                    :max="1"
                    :step="0.05"
                    class="w-full"
                  />
                  <span class="text-sm">{{ watermarkOpacity[0] }}</span>
                </div>
                <div>
                  <Label class="block my-2">边框粗细</Label>
                  <Slider
                    v-model="borderWidth"
                    :min="0"
                    :max="10"
                    :step="1"
                    class="w-100"
                  />
                  <span class="text-sm">{{ borderWidth[0] }}</span>
                </div>
                <div>
                  <Label class="block my-2">圆角</Label>
                  <Slider
                    v-model="borderRadius"
                    :min="0"
                    :max="40"
                    :step="1"
                    class="w-100"
                  />
                  <span class="text-sm">{{ borderRadius[0] }}</span>
                </div>
              </div>
            </div>
          </div>
        </ScrollArea>
        <!-- 右侧预览与操作区域 -->
        <div
          class="flex-1 flex flex-col rounded-md border p-4 h-[600px] bg-white"
        >
          <!-- 预览区域 -->
          <div
            class="flex-1 flex flex-col justify-center items-center relative"
          >
            <div class="flex items-center gap-2"></div>
            <div
              class="absolute left-0 top-0 text-lg font-medium mb-4 ml-2 mt-2 z-10"
            >
              预览效果
            </div>
            <div
              id="export-preview-area"
              class="relative overflow-hidden rounded-lg shadow-lg"
              :class="currentTemplate.containerClass"
              :style="{
                border: borderWidth[0] + 'px solid #e5e7eb',
                borderRadius: borderRadius[0] + 'px',
              }"
            >
              <!-- 动态模板渲染 -->
              <template v-if="currentTemplate.render === 'bottomText'">
                <img
                  :src="selectedImages[0]?.url"
                  class="w-full h-full object-cover"
                />
                <div
                  :class="[
                    'absolute left-0 right-0 bottom-0',
                    currentTemplate.textBg,
                    'p-4',
                    'text-center',
                  ]"
                >
                  <span :class="currentTemplate.textStyle">{{
                    copywritingText
                  }}</span>
                </div>
              </template>
              <template v-else-if="currentTemplate.render === 'centerOverlay'">
                <img
                  :src="selectedImages[0]?.url"
                  class="w-full h-full object-cover"
                />
                <div
                  class="absolute inset-0 flex items-center justify-center"
                  :style="{ background: currentTemplate.overlayColor }"
                >
                  <span
                    :class="currentTemplate.textStyle"
                    :style="{ color: currentTemplate.textColor }"
                    >{{ copywritingText }}</span
                  >
                </div>
              </template>
              <template v-else-if="currentTemplate.render === 'topBanner'">
                <img
                  :src="selectedImages[0]?.url"
                  class="w-full h-full object-cover"
                />
                <div
                  :class="[
                    'absolute left-0 right-0 top-0',
                    currentTemplate.bannerBg,
                    'p-3',
                    'text-center',
                    'rounded-t-lg',
                  ]"
                >
                  <span :class="currentTemplate.textStyle">{{
                    copywritingText
                  }}</span>
                </div>
              </template>
              <template v-else-if="currentTemplate.render === 'leftBadge'">
                <img
                  :src="selectedImages[0]?.url"
                  class="w-full h-full object-cover"
                />
                <div
                  :class="[
                    'absolute left-2 bottom-2 px-3 py-1 rounded',
                    currentTemplate.badgeBg,
                  ]"
                >
                  <span :class="currentTemplate.textStyle">{{
                    copywritingText
                  }}</span>
                </div>
              </template>
              <template v-else-if="currentTemplate.render === 'rightRibbon'">
                <img
                  :src="selectedImages[0]?.url"
                  class="w-full h-full object-cover"
                />
                <div
                  :class="[
                    'absolute right-2 top-2 px-3 py-1 rounded-full shadow',
                    currentTemplate.ribbonBg,
                  ]"
                >
                  <span :class="currentTemplate.textStyle">{{
                    copywritingText
                  }}</span>
                </div>
              </template>
              <!-- 兼容原有模板 -->
              <template v-else>
                <img
                  :src="selectedImages[0]?.url || ''"
                  :alt="selectedImages[0]?.name || ''"
                  class="w-full h-full object-cover"
                />
                <div class="bg-gray-100 p-4 flex items-center justify-center">
                  <p class="text-gray-800 text-center font-medium">
                    {{ copywritingText || "✨ 限时特惠! 精选好物, 不容错过!" }}
                  </p>
                </div>
              </template>
              <!-- 水印 -->
              <div
                v-if="watermarkText"
                class="absolute left-0 top-0 w-full h-full pointer-events-none select-none flex items-center justify-center z-20"
                :style="{ opacity: watermarkOpacity[0] }"
              >
                <span
                  class="text-4xl font-bold text-gray-400 whitespace-nowrap"
                  style="transform: rotate(-20deg)"
                  >{{ watermarkText }}</span
                >
              </div>
            </div>
          </div>
          <!-- 功能按钮区 -->
          <div
            class="flex justify-end gap-3 mt-4 pt-4 border-t border-gray-200 items-center"
          >
            <Label class="mr-2 text-sm">导出格式：</Label>
            <Select v-model="exportFormat">
              <SelectTrigger class="w-32">
                <span>{{
                  exportFormat === "jpg"
                    ? "JPG图片"
                    : exportFormat === "pdf"
                    ? "PDF文档"
                    : exportFormat === "h5"
                    ? "H5页面"
                    : ""
                }}</span>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="jpg">JPG图片</SelectItem>
                <SelectItem value="pdf">PDF文档</SelectItem>
                <SelectItem value="h5">H5页面</SelectItem>
              </SelectContent>
            </Select>
            <Button @click="exportImage">导出</Button>
          </div>
        </div>
      </TabsContent>

      <!-- AI 导出模式 -->
      <TabsContent value="ai" class="flex gap-6 flex-1 min-h-0">
        <!-- 左侧配置区域 -->
        <ScrollArea
          class="w-100 rounded-md border p-4 h-[600px] flex-shrink-0 bg-white"
        >
          <div class="space-y-6">
            <!-- 选中图片展示 -->
            <div>
              <div class="text-lg font-semibold mb-3">选中图片</div>
              <div class="flex gap-3 overflow-x-auto pb-2">
                <div
                  v-for="(img, index) in selectedImages"
                  :key="img.id"
                  class="relative flex-shrink-0"
                >
                  <div
                    class="w-20 h-20 rounded-lg overflow-hidden border-2 border-gray-200"
                  >
                    <img
                      :src="img.url"
                      :alt="img.name"
                      class="w-full h-full object-cover"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- AI 生成按钮 -->
            <div class="mt-6">
              <Button
                @click="generateAiExport"
                :disabled="isAiGenerating || selectedImages.length === 0"
                class="w-full flex items-center justify-center gap-2"
                size="lg"
              >
                <svg
                  v-if="isAiGenerating"
                  class="w-5 h-5 animate-spin"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                  />
                </svg>
                <svg
                  v-else
                  class="w-5 h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M13 10V3L4 14h7v7l9-11h-7z"
                  />
                </svg>
                {{ isAiGenerating ? "AI 生成中..." : "AI 生成" }}
              </Button>
            </div>
          </div>
        </ScrollArea>

        <!-- 右侧预览与操作区域 -->
        <div
          class="flex-1 flex flex-col rounded-md border p-4 h-[600px] bg-white"
        >
          <!-- 预览区域 -->
          <div
            class="flex-1 flex flex-col justify-center items-center relative"
          >
            <!-- AI 生成状态 -->
            <div
              v-if="isAiGenerating"
              class="flex flex-col items-center justify-center h-full gap-6"
            >
              <div class="relative">
                <svg
                  class="w-16 h-16 animate-spin text-primary"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                  />
                </svg>
              </div>
              <div class="text-center max-w-sm">
                <div class="text-xl font-semibold text-gray-900 mb-2">
                  AI 正在生成海报
                </div>
                <div class="text-sm text-gray-600 leading-relaxed">
                  请稍候，我们正在为您创建精美的海报内容，这可能需要几秒钟时间
                </div>
              </div>
            </div>

            <!-- AI 生成结果 -->
            <div
              v-else-if="aiGeneratedResults.length > 0"
              class="w-full h-full overflow-y-auto p-4"
            >
              <div class="space-y-4">
                <div
                  v-for="(result, index) in aiGeneratedResults"
                  :key="index"
                  class="bg-white border rounded-lg shadow-sm overflow-hidden"
                >
                  <!-- 头部信息 -->
                  <div
                    class="flex items-center justify-between p-4 border-b bg-gray-50"
                  >
                    <div class="flex items-center gap-2">
                      <span class="font-medium text-gray-900">{{
                        result.description
                      }}</span>
                      <span
                        class="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full font-medium"
                      >
                        {{ result.type === "poster" ? "海报" : "内容" }}
                      </span>
                    </div>
                    <Button
                      size="sm"
                      variant="outline"
                      @click="downloadAiResult(result)"
                      class="flex items-center gap-1"
                    >
                      <svg
                        class="w-3 h-3"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                        />
                      </svg>
                      下载
                    </Button>
                  </div>

                  <!-- 内容区域 -->
                  <div class="p-4">
                    <!-- 如果是海报类型，显示图片 -->
                    <div
                      v-if="result.type === 'poster'"
                      class="flex justify-center"
                    >
                      <div
                        class="max-w-full max-h-96 overflow-hidden rounded-lg"
                      >
                        <img
                          :src="result.content"
                          :alt="result.description"
                          class="w-full h-auto max-h-96 object-contain rounded-lg shadow-sm"
                          @error="handleImageError"
                        />
                      </div>
                    </div>

                    <!-- 如果是文本内容，显示文本 -->
                    <div v-else class="bg-gray-50 rounded-lg p-3">
                      <div class="text-sm text-gray-800 leading-relaxed">
                        {{ result.content }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 默认状态 -->
            <div
              v-else
              class="flex flex-col items-center justify-center h-full gap-6"
            >
              <div class="relative">
                <svg
                  t="1753021733862"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="40000"
                  width="200"
                  height="200"
                >
                  <path
                    d="M565.096296 289.185185s-0.948148 0 0 0c-110.933333-20.859259-208.592593 40.77037-237.985185 148.859259-14.222222 53.096296-24.651852 101.451852 44.562963 221.866667 14.222222 25.6 11.377778 70.162963 8.533333 95.762963-1.896296 14.222222 64.474074 36.02963 89.125926 42.666667l95.762963-509.155556z"
                    fill="#FDB813"
                    p-id="40001"
                  ></path>
                  <path
                    d="M732.918519 513.896296c11.377778-111.881481-56.888889-203.851852-166.874075-224.711111h-0.948148L469.333333 798.340741c25.6 2.844444 94.814815 6.637037 98.607408-7.585185 6.637037-25.6 20.859259-67.318519 42.666666-86.281482C719.644444 618.192593 727.22963 568.888889 732.918519 513.896296z"
                    fill="#FD9B13"
                    p-id="40002"
                  ></path>
                  <path
                    d="M467.437037 806.874074c-7.585185-0.948148-12.325926-7.585185-14.222222-14.222222l-38.874074-256c-0.948148-5.688889 0.948148-11.377778 4.74074-15.170371 3.792593-3.792593 9.481481-5.688889 15.170371-4.74074l167.822222 31.288889c5.688889 0.948148 10.42963 4.740741 12.325926 9.481481 1.896296 4.740741 1.896296 11.377778-0.948148 16.118519L486.4 798.340741c-3.792593 6.637037-11.377778 10.42963-18.962963 8.533333z m-14.222222-251.259259l27.496296 182.992592L572.681481 578.37037l-119.466666-22.755555z"
                    fill="#F12A3F"
                    p-id="40003"
                  ></path>
                  <path
                    d="M375.466667 709.214815l-25.6 137.481481c0 2.844444 1.896296 5.688889 7.585185 10.42963l65.422222 54.992593c5.688889 4.740741 15.17037 8.533333 23.703704 10.429629l36.029629-193.422222-107.14074-19.911111z"
                    fill="#2D4375"
                    p-id="40004"
                  ></path>
                  <path
                    d="M482.607407 729.125926l-36.029629 193.422222c9.481481 1.896296 18.014815 1.896296 25.6-0.948148l80.592592-27.496296c6.637037-1.896296 10.42963-4.740741 11.377778-6.637037L589.748148 749.037037l-107.140741-19.911111z"
                    fill="#1E2D4F"
                    p-id="40005"
                  ></path>
                  <path
                    d="M612.503704 217.125926c-3.792593 18.014815-20.859259 29.392593-38.874074 26.548148-18.014815-3.792593-30.340741-20.859259-26.548149-38.874074l18.962963-100.503704c3.792593-18.014815 20.859259-29.392593 38.874075-26.548148 18.014815 3.792593 30.340741 20.859259 26.548148 38.874074l-18.962963 100.503704z"
                    fill="#FDB813"
                    p-id="40006"
                  ></path>
                  <path
                    d="M382.103704 228.503704c10.42963 15.17037 6.637037 36.02963-8.533334 46.459259-15.17037 10.42963-36.02963 6.637037-46.459259-8.533333l-57.837037-84.385186c-10.42963-15.17037-6.637037-36.02963 8.533333-46.459259 15.17037-10.42963 36.02963-6.637037 46.45926 8.533334l57.837037 84.385185zM757.57037 298.666667c-15.17037 10.42963-18.962963 31.288889-8.533333 46.459259 10.42963 15.17037 31.288889 18.962963 46.459259 8.533333l84.385185-57.837037c15.17037-10.42963 18.962963-31.288889 8.533334-46.459259-10.42963-15.17037-31.288889-18.962963-46.459259-8.533333l-84.385186 57.837037z"
                    fill="#FDB813"
                    p-id="40007"
                  ></path>
                  <path
                    d="M252.207407 361.244444c18.014815 3.792593 30.340741 20.859259 26.548149 38.874075-3.792593 18.014815-20.859259 29.392593-38.874075 26.548148l-100.503703-18.962963c-18.014815-3.792593-30.340741-20.859259-26.548148-38.874074 3.792593-18.014815 20.859259-29.392593 38.874074-26.548149l100.503703 18.962963zM931.081481 488.296296c18.014815 3.792593 30.340741 20.859259 26.548149 38.874074-3.792593 18.014815-20.859259 29.392593-38.874074 26.548149l-100.503704-18.962963c-18.014815-3.792593-30.340741-20.859259-26.548148-38.874075 3.792593-18.014815 20.859259-29.392593 38.874074-26.548148l100.503703 18.962963z"
                    fill="#FDB813"
                    p-id="40008"
                  ></path>
                  <path
                    d="M593.540741 807.822222c1.896296-7.585185-3.792593-15.17037-11.377778-16.118518l-107.140741-19.911111-4.740741 27.496296 107.140741 19.911111c6.637037 0.948148 14.222222-3.792593 16.118519-11.377778z"
                    fill="#CEEFF6"
                    p-id="40009"
                  ></path>
                  <path
                    d="M366.933333 750.933333c-7.585185-1.896296-15.17037 3.792593-16.118518 11.377778-1.896296 7.585185 3.792593 15.17037 11.377778 16.118519l107.14074 19.911111 4.740741-27.496297-107.140741-19.911111zM356.503704 808.77037c-7.585185-1.896296-15.17037 3.792593-16.118519 11.377778-1.896296 7.585185 3.792593 15.17037 11.377778 16.118519l107.140741 19.911111 4.74074-27.496297-107.14074-19.911111z"
                    fill="#FFFFFF"
                    p-id="40010"
                  ></path>
                  <path
                    d="M570.785185 848.592593l-107.140741-19.911112-4.74074 27.496297 107.14074 19.911111c7.585185 1.896296 15.17037-3.792593 16.118519-11.377778 1.896296-7.585185-2.844444-15.17037-11.377778-16.118518z"
                    fill="#CEEFF6"
                    p-id="40011"
                  ></path>
                </svg>
              </div>
              <div class="text-center max-w-sm">
                <div class="text-xl font-semibold text-gray-900 mb-2">
                  AI 智能海报生成
                </div>
                <div class="text-sm text-gray-600 leading-relaxed">
                  选择图片后点击左侧的 AI 生成按钮，AI 将为您创建精美的海报内容
                </div>
              </div>
            </div>
          </div>

          <!-- 功能按钮区 -->
          <div class="flex justify-end gap-3 pt-4 items-center">
            <Label class="mr-2 text-sm">导出格式：</Label>
            <Select v-model="aiExportFormat">
              <SelectTrigger class="w-32">
                <span>{{
                  aiExportFormat === "jpg"
                    ? "JPG图片"
                    : aiExportFormat === "pdf"
                    ? "PDF文档"
                    : aiExportFormat === "h5"
                    ? "H5页面"
                    : ""
                }}</span>
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="jpg">JPG图片</SelectItem>
                <SelectItem value="pdf">PDF文档</SelectItem>
                <SelectItem value="h5">H5页面</SelectItem>
              </SelectContent>
            </Select>
            <Button
              @click="exportAiImage"
              :disabled="aiGeneratedResults.length === 0"
              >导出</Button
            >
            <Button
              variant="outline"
              @click="shareAiResult"
              :disabled="aiGeneratedResults.length === 0"
            >
              <svg
                class="w-4 h-4 mr-2"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"
                />
              </svg>
              分享
            </Button>
          </div>
        </div>
      </TabsContent>
    </Tabs>
  </main>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useMaterialStore } from "../stores/material";
import { Button } from "../components/ui/button";
import { ScrollArea } from "../components/ui/scroll-area";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Slider } from "../components/ui/slider";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
} from "../components/ui/select";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "../components/ui/tabs";
import { Textarea } from "../components/ui/textarea";
import jsPDF from "jspdf";
import domtoimage from "dom-to-image-more";
import confetti from "canvas-confetti";
import { toast } from "vue-sonner";
import { generatePoster } from "../api/imageGenerate";

// 移除无用的@ts-expect-error注释
// eslint-disable-next-line
declare module "dom-to-image-more";

const materialStore = useMaterialStore();

// 通用复制到剪贴板函数
function copyToClipboard(text: string) {
  // 优先使用现代 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        toast("复制成功", { description: "内容已复制到剪贴板" });
      })
      .catch(err => {
        console.warn("Clipboard API 失败，使用降级方案:", err);
        fallbackCopyToClipboard(text);
      });
  } else {
    // 降级方案：使用传统的 document.execCommand
    fallbackCopyToClipboard(text);
  }
}

// 降级复制方案
function fallbackCopyToClipboard(text: string) {
  try {
    // 创建临时文本区域
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);

    // 选择文本并复制
    textArea.focus();
    textArea.select();
    const successful = document.execCommand("copy");

    // 清理临时元素
    document.body.removeChild(textArea);

    if (successful) {
      toast("复制成功", { description: "内容已复制到剪贴板" });
    } else {
      toast("复制失败", { description: "请手动复制内容" });
    }
  } catch (err) {
    console.error("复制失败:", err);
    toast("复制失败", { description: "请手动复制内容" });
  }
}

// 获取从素材库选择的图片
const selectedImages = computed(() => materialStore.selectedImages);

// 模板配置
const templates = [
  {
    key: "bottomText",
    label: "底部文案单图",
    ratio: "1:1",
    containerClass: "w-80 h-80",
    render: "bottomText",
    textStyle: "font-bold text-lg",
    textBg: "bg-white/80",
    textAlign: "center",
    iconWidth: 18,
    iconHeight: 18,
  },
  {
    key: "centerOverlay",
    label: "中央蒙层文案",
    ratio: "3:4",
    containerClass: "w-80 h-96",
    render: "centerOverlay",
    overlayColor: "rgba(0,0,0,0.4)",
    textColor: "#fff",
    textStyle: "font-bold text-xl",
    textAlign: "center",
    iconWidth: 14,
    iconHeight: 18,
  },
  {
    key: "topBanner",
    label: "顶部横幅文案",
    ratio: "16:9",
    containerClass: "w-96 h-54",
    render: "topBanner",
    bannerBg: "bg-primary/90",
    textStyle: "font-bold text-base text-white",
    iconWidth: 18,
    iconHeight: 10,
  },
  {
    key: "leftBadge",
    label: "左下角角标文案",
    ratio: "1:1",
    containerClass: "w-80 h-80",
    render: "leftBadge",
    badgeBg: "bg-red-500",
    textStyle: "font-bold text-xs text-white",
    iconWidth: 18,
    iconHeight: 18,
  },
  {
    key: "rightRibbon",
    label: "右上角徽章文案",
    ratio: "1:1",
    containerClass: "w-80 h-80",
    render: "rightRibbon",
    ribbonBg: "bg-green-500",
    textStyle: "font-bold text-xs text-white",
    iconWidth: 18,
    iconHeight: 18,
  },
];

const activeTab = ref("manual");
const selectedTemplate = ref("bottomText");
const copywritingText = ref("✨ 限时特惠! 精选好物, 不容错过!");

// 导出格式
const exportFormat = ref("jpg"); // 'jpg' | 'pdf' | 'h5'
// 水印、边框、品牌信息设置
const watermarkText = ref("演示水印");
const watermarkOpacity = ref([0.2]);
// 移除 borderColor, brandName, brandLogo 相关内容
// 只保留 borderWidth 和 borderRadius，均用 Slider 控件
const borderWidth = ref([2]);
const borderRadius = ref([16]);
// 移除 borderColor, brandName, brandLogo 相关的 ref、onLogoChange、模板渲染等
// 导出时 borderColor 固定为 #e5e7eb
const brandLogo = ref(""); // base64

// AI 导出相关
const aiExportFormat = ref("jpg");
const isAiGenerating = ref(false);
const aiGeneratedResults = ref<any[]>([]);

function onLogoChange(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = () => {
      brandLogo.value = reader.result as string;
    };
    reader.readAsDataURL(file);
  }
}

// 预览容器样式
const currentTemplate = computed(
  () => templates.find(t => t.key === selectedTemplate.value) || templates[0]
);

// 工具函数：将oklch颜色转为rgb
function oklchToRgb(oklchStr: string) {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return oklchStr;
  ctx.fillStyle = oklchStr;
  return ctx.fillStyle;
}

// 递归替换所有oklch颜色为rgb
function replaceOklchWithRgb(el: HTMLElement) {
  if (!el) return;
  const style = window.getComputedStyle(el);
  for (const key of Object.keys(style)) {
    const val = style.getPropertyValue(key);
    if (val && val.includes("oklch(")) {
      const rgb = oklchToRgb(val);
      el.style.setProperty(key, rgb, "important");
    }
  }
  // 递归子节点
  for (const child of el.children) {
    replaceOklchWithRgb(child as HTMLElement);
  }
}

// 导出功能
async function exportImage() {
  const previewEl = document.getElementById("export-preview-area");
  if (!previewEl) return;
  // 导出前替换oklch为rgb
  replaceOklchWithRgb(previewEl);
  let success = false;
  if (exportFormat.value === "jpg") {
    const dataUrl = await domtoimage.toJpeg(previewEl, {
      quality: 0.95,
      bgcolor: null,
    });
    const link = document.createElement("a");
    link.href = dataUrl;
    link.download = "export.jpg";
    link.click();
    success = true;
  } else if (exportFormat.value === "pdf") {
    const dataUrl = await domtoimage.toJpeg(previewEl, {
      quality: 0.95,
      bgcolor: null,
    });
    const img = new window.Image();
    img.src = dataUrl;
    img.onload = () => {
      const pdf = new jsPDF({
        orientation: "portrait",
        unit: "px",
        format: [img.width, img.height],
      });
      pdf.addImage(dataUrl, "JPEG", 0, 0, img.width, img.height);
      pdf.save("export.pdf");
      toast("导出成功", { description: "您的内容已成功导出！" });
      confetti({ particleCount: 100, spread: 70, origin: { y: 0.6 } });
    };
    return;
  } else if (exportFormat.value === "h5") {
    const htmlContent = previewEl.outerHTML;
    const fullHtml = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@3.4.3/dist/tailwind.min.css" rel="stylesheet">
  <title>导出内容</title>
  <style>body { background: #f8fafc; }</style>
</head>
<body>
  ${htmlContent}
</body>
</html>
`;
    const blob = new Blob([fullHtml], { type: "text/html" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "export.html";
    link.click();
    success = true;
  }
  if (success) {
    toast("导出成功", { description: "您的内容已成功导出！" });
    confetti({ particleCount: 300, spread: 180, origin: { y: 0.6 } });
  }
}

// AI 导出功能
async function generateAiExport() {
  if (selectedImages.value.length === 0) {
    toast("请选择图片", { description: "请先选择要导出的图片。" });
    return;
  }

  isAiGenerating.value = true;
  aiGeneratedResults.value = [];
  toast("AI 导出中...", { description: "请稍候，AI 正在为您生成海报。" });

  try {
    // 使用海报生成接口
    const imageId = selectedImages.value[0].id;
    const prompt = `基于这张图片生成精美的海报，包含以下元素：
1. 保持原图的视觉风格和主题
2. 添加合适的标题和文案
3. 优化布局和排版
4. 增强视觉效果和吸引力
5. 适合社交媒体分享`;

    const result = await generatePoster({
      imageId: Number(imageId),
      prompt: prompt,
    });

    if (result.success && result.data) {
      aiGeneratedResults.value = [
        {
          description: "AI 生成海报",
          content: result.data,
          type: "poster",
        },
      ];
      toast("AI 导出成功", { description: "海报已生成完成！" });
    } else {
      throw new Error(result.message || "生成失败");
    }
  } catch (error) {
    console.error("AI 导出失败:", error);
    toast("AI 导出失败", { description: "海报生成失败，请稍后再试。" });
  } finally {
    isAiGenerating.value = false;
  }
}

function downloadAiResult(result: any) {
  if (result.type === "poster") {
    // 对于海报图片，直接下载
    const link = document.createElement("a");
    link.href = result.content;
    link.download = `${result.description || "ai_poster"}.jpg`;
    link.click();
    toast("下载成功", { description: `${result.description} 已下载。` });
  } else {
    // 对于文本内容，复制到剪贴板
    copyToClipboard(result.content);
  }
}

// AI 导出功能
async function exportAiImage() {
  if (aiGeneratedResults.value.length === 0) {
    toast("请先生成内容", { description: "请先使用 AI 生成内容。" });
    return;
  }

  // 这里可以根据需要实现 AI 内容的导出功能
  // 目前简单下载第一个结果
  if (aiGeneratedResults.value[0]) {
    downloadAiResult(aiGeneratedResults.value[0]);
  }
}

// AI 分享功能
function shareAiResult() {
  if (aiGeneratedResults.value.length === 0) {
    toast("请先生成内容", { description: "请先使用 AI 生成内容。" });
    return;
  }

  // 这里可以实现分享功能，比如复制链接、生成分享码等
  toast("分享功能", { description: "分享功能开发中..." });
}

// 处理图片加载错误
function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement;
  img.style.display = "none";
  const container = img.parentElement;
  if (container) {
    container.innerHTML =
      '<div class="text-center text-gray-500 py-8">图片加载失败</div>';
  }
}

onMounted(() => {
  if (
    materialStore.selectedImageForAction &&
    (!materialStore.selectedImageIds.length ||
      materialStore.selectedImageIds.length !== 1 ||
      materialStore.selectedImageIds[0] !==
        materialStore.selectedImageForAction.id)
  ) {
    materialStore.selectedImageIds = [materialStore.selectedImageForAction.id];
  }
});
</script>
